# -*- coding: utf-8 -*-
# @Time    : 2018/2/5 13:11
# @Author  : Soft
# @File    : view.py
# @Desc    : 后台管理的视图
import qrcode
import base64
import io

from module.TimeUtils import *
from module.admin import admin, ad_login
from flask import render_template, request, jsonify

from module.location.Service import LocalService
from module.user.service import StuService
from module.class_.service import ClzService, Class
from module.record.service import ReService
from module.work.service import WorkService
from module.cache import cache
from config import Img, Check, QR_Auto_Flush
from module.z_study.service import Z_StudyService


@admin.route('/plan')
@ad_login.required
def plan():  # 按年度展示课程列表 如果有几年的就显示今年的 如果只有一年的就显示该年
    year = request.args.get('year')
    page = request.args.get('page', '1')
    if not year:
        year = get_year()
    y_group = ClzService.get_year_group()
    if len(y_group) == 1:
        year = y_group[0].get('k_time')
    years = [year]
    years.extend(y_group)
    plans = ClzService.pages(page=int(page), year=year)
    stu_all = StuService.stu_count(year=year)
    return render_template('admin/plan.html', name=ad_login.get_user_name(), plan_list=plans,
                           years=years, stu_all=stu_all)


@admin.route('/plan-ac')
def plan_ac():
    cid = request.args.get('id', '0')
    clz = Class.find_by_id(int(cid))
    ls = LocalService.getAll()
    return render_template('admin/plan-ac.html', clazz=clz, cid=int(cid), locals=ls)


@admin.route('/work')
@ad_login.required
def work():
    year = get_year()
    years = [year]
    y_group = ClzService.get_year_group()
    if len(y_group) == 1:
        year = y_group[0].get('k_time')
    years.extend(y_group)
    clzs = ClzService.by_year(year=year)
    stus = StuService.by_year(year=year)
    work_list = WorkService.pages(page=1, year=year)
    return render_template('admin/work.html', name=ad_login.get_user_name(), work_list=work_list, years=years,
                           clzs=clzs, stus=stus)


@admin.route('/student')
@ad_login.required
def student():
    year = request.args.get('year')
    page = request.args.get('page', '1')
    if not year:
        year = get_year()
    y_group = StuService.get_year_group()
    if len(y_group) == 1:
        year = y_group[0].get('stu_reg_time')
    years = [year]
    years.extend(y_group)
    stu_list = StuService.pages(page=int(page), year=year)
    return render_template('admin/student.html', name=ad_login.get_user_name(), stu_list=stu_list,
                           years=years)


@admin.route('/record')
@ad_login.required
def record():
    kid = int(request.args.get('kid', '0'))
    year = request.args.get('year')
    if not year:
        year = get_year()
    y_group = ClzService.get_year_group()
    if len(y_group) == 1:
        year = y_group[0].get('k_time')

    clzs = ClzService.by_year(year=year)
    stus = StuService.by_year(year=year)
    record_list = ReService.pages(page=1, year=year, k_id=kid)
    return render_template('admin/record.html', name=ad_login.get_user_name(), record_list=record_list,
                           years=y_group, clzs=clzs, stus=stus, year=year, kid=kid)


@admin.route('/online')
@ad_login.required
def online():
    cache.set(Img.C_AUTH, str(time.time())[:-1])
    qd_url = None
    now_date = get_date()
    data = dict(need=False, k_has=False, is_study=False)
    k_can = ClzService.by_k_time(k_time=now_date)
    if k_can[0] is not False:
        qd_url = request.host_url + 'record/check_in/' + str(k_can[1].id) + '?flag=' + request.host
        print(qd_url)
        cache.set(Img.C_URL, qd_url)
        Img.QR_URL = get_img_url(qd_url + '&tl=' + cache.get(Img.C_AUTH))
        # # #
        cache.set('clazz', k_can[1])  # 在缓存中保存当前签到课程
        data['k_has'] = True  # 今日有没有课程
        data.setdefault('clazz', k_can[1])
        data.setdefault('img_url', Img.QR_URL)
        k_start_time = k_can[1].k_time
        if check_limit(k_start_time) == Check.CD or check_limit(k_start_time) == Check.CQ:
            data['need'] = True  # 该时间段是否可以签到
        else:
            data['need'] = Check.ALL_DAY_CHECK
    # 这里以上课时间为优先 有课则不需要进行自习签到
    if not data['need']:
        if Z_StudyService.can_check():
            qd_url = request.host_url + 'study/add_record'
            cache.set(Img.C_URL, qd_url)
            Img.QR_URL = get_img_url(qd_url + '?tl=' + cache.get(Img.C_AUTH))
            data['need'] = True
            data['img_url'] = Img.QR_URL
            data['is_study'] = True
            if cache in ['clazz']:
                cache.pop('clazz')  # 清除缓存中的课程信息
    # print cache.get(Img.C_AUTH)
    return render_template('admin/online.html', name=ad_login.get_user_name(), info=data,
                           qd_url=qd_url, auto_flush=QR_Auto_Flush * 1000, all_day=Check.ALL_DAY_CHECK)


@admin.route('/flush_img', methods=['post'])
@ad_login.required
def flush_img():
    cache.set(Img.C_AUTH, str(time.time())[:-1])
    need = Check.ALL_DAY_CHECK
    if cache.has_key('clazz'):
        k_start_time = cache.get('clazz').k_time
        if check_limit(k_start_time) == Check.CD or check_limit(k_start_time) == Check.CQ:
            need = True  # 该时间段是否可以签到
    else:
        if Z_StudyService.can_check():
            need = True
    Img.QR_URL = get_img_url(cache.get(Img.C_URL) + '?tl=' + cache.get(Img.C_AUTH))
    return jsonify(status=True, img_url=Img.QR_URL, need=need)


# 2020-03-28
# 直接修改成生成二维码
def get_img_url(qd_url):
    # try:
    #     data = bytes(
    #         urllib.parse.urlencode({
    #             'code': qd_url,
    #             'auth': 'lkl123456'
    #         })
    #     )
    #     res = urllib.request.urlopen(url='http://123.206.7.80:10082/api/create', data=data)
    #     return json.loads(res.read()).get('payload').get('url')
    # except BaseException as e:
    #     print(e)
    # return ''
    img = qrcode.make(qd_url)
    buf = io.BytesIO()
    img.save(buf, format='PNG')
    img_stream = buf.getvalue()
    HexImg = base64.b64encode(img_stream)
    return 'data:image/png;base64,' + HexImg.decode()


###############
@admin.route('/z_study', methods=['get'])
@ad_login.required
def z_study():
    page = int(request.args.get('page', '1'))
    year = request.args.get('year')
    if not year:
        year = get_year()
    y_group = StuService.get_year_group()
    if len(y_group) == 1:
        year = y_group[0].get('stu_reg_time')

    stus = StuService.by_year(year=year)
    record_list = Z_StudyService.query(page=page, start=get_date(-5) + " 00:00", end=get_date(5) + " 23:59")
    return render_template('admin/z-record.html', name=ad_login.get_user_name(),
                           years=y_group, stus=stus, year=year, record_list=record_list)


@admin.route('/input_location')
@ad_login.required
def input_location():
    ls = LocalService.getAll()
    return render_template('admin/Input_location.html', name=ad_login.get_user_name(),
                           locals=ls, local=cache.get("local"))
